<template>
  <div class="table-list">
    <el-table
      ref="multipleTableRef"
      id="exportDom"
      :data="tableData"
      style="width: 100%; height: 100%"
      border
      tooltip-effect="light"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <!-- <el-table-column label="Date" width="120">
        <template #default="scope">{{ scope.row.date }}</template>
      </el-table-column> -->
      <el-table-column width="60" property="ID" label="ID" />
      <el-table-column
        property="标题"
        label="标题"
        width="120"
        show-overflow-tooltip
      />
      <el-table-column property="内容" label="内容" show-overflow-tooltip />
    </el-table>
  </div>

  <div class="pagination-list">
    <div>
      <el-button type="success" style="margin-left: 10px" @click="submit"
        >数据发布</el-button
      >
      <el-button type="primary" @click="dialogVisible = true"
        >文件导入</el-button
      >
      <el-popover
        :visible="visible"
        title="导出数据"
        placement="top"
        :width="300"
      >
        <div class="export-sty">
          <span>文件名：</span>
          <el-input
            v-model="exportName"
            style="width: 150px"
            placeholder="请输入导出文件名"
          />
        </div>
        <div style="text-align: right; margin: 0">
          <el-button size="small" @click="visible = false">取消</el-button>
          <el-button size="small" type="primary" @click="exportFile"
            >确定</el-button
          >
        </div>
        <template #reference>
          <el-button @click="visible = true" type="primary">文件导出</el-button>
        </template>
      </el-popover>
      <el-button type="primary" @click="calcelSend">取消定时发布</el-button>
      <el-popover
        placement="top-start"
        title="发布成功/失败分析:"
        :width="800"
        trigger="hover"
      >
        <div class="tip-send">
          <div class="success-send">
            <span>一。发布成功示例：</span>
            <img src="../../../image/success.png" alt="" />
          </div>
          <div class="fail-send">
            <span>
              二、出现以下提示，则代表cookie
              失效，去网站后台发布一篇文章，然后复制发布接口的cookie到后台即可：<br />
              <span
                >1、后台发布数据，接口的状态为：403，且接口的预览属性提示：浏览器不支持javascript,页面无法访问！
              </span>
            </span>
          </div>
          <div style="line-height: 28px">
            三、发布数据之前，请先关闭网站 http 强制转换为
            https，否则，会出现跨域，无法发布数据（关闭 RewriteRule ^(.*)$
            https://www.xinxi00.com/$1 [R=301,L]
            https：打开网站根目录，找到.htaccess文件，将下面的代码通过（#）注释掉）1、RewriteEngine
            On；2、RewriteCond %{HTTP_HOST} ^baidu.com$ [NC]；3、RewriteRule
            ^(.*)$ https://www.baidu.com/$1 [R=301,L]
          </div>
        </div>
        <template #reference>
          <el-button type="info" class="m-2">发布成功/失败示例</el-button>
        </template>
      </el-popover>
    </div>
    <el-pagination
      v-model:current-page="currentPage4"
      v-model:page-size="pageSize4"
      :page-sizes="[10, 20, 30, 50, 100, 200, 300, 500, 1000, 2000, 5000, 10000]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <div>
    <el-drawer v-model="drawer" title="发布配置信息" size="50%">
      <div class="input-box">
        <div class="box-title">cookie：</div>
        <el-input
          v-model="cookieValue"
          placeholder="请输入发布网站的 cookie"
          type="textarea"
          :rows="3"
          style="width: 70%"
        />
      </div>
      <div class="input-box">
        <div class="box-title">Content-Type：</div>
        <el-input
          v-model="contentTypeValue"
          placeholder="请输入发布网站的 Content-Type"
          type="textarea"
          :rows="3"
          style="width: 70%"
        />
      </div>
      <div class="input-box">
        <div class="box-title">参数：</div>
        <el-input
          v-model="paramValue"
          placeholder="请输入发布网站的参数"
          type="textarea"
          :rows="5"
          style="width: 70%"
        />
      </div>
      <div class="input-box">
        <div class="box-title">网站链接：</div>
        <el-input
          v-model="urlValue"
          placeholder="请输入发布网站的链接"
          :rows="5"
          style="width: 70%"
        />
      </div>
      <div class="input-box">
        <span class="box-title">开启定时发布：</span>
        <el-switch v-model="switchValue" />
      </div>
      <div class="input-box" v-if="switchValue">
        <div class="box-title">定时发布时间：</div>
        <el-input
          v-model="setTimeValue"
          placeholder="请输入定时发布时间"
          :rows="5"
          style="width: 70%"
        >
          <template #prepend>间隔</template>
          <template #append>分钟发布一次</template></el-input
        >
      </div>
      <div class="demo-drawer__footer footer-sty">
        <el-button size="large" @click="drawer = false">取消发布</el-button>
        <el-button
          size="large"
          type="primary"
          @click="mergeData"
          :disabled="btnDisabled"
          >立即发布</el-button
        >
      </div>
    </el-drawer>
  </div>

  <!-- 文件上传 -->
  <div>
    <el-dialog v-model="dialogVisible" title="" width="50%">
      <template #header="{ titleId }">
        <span :id="titleId" class="import-tip">
          <el-icon :size="30" color="#E6A23C"> <Warning /> </el-icon
          >&nbsp;注意：导入文件，当前表格数据会被清除</span
        >
      </template>
      <FileImport @fileImportResult="fileImportResult" />
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref, h, onBeforeUnmount } from "vue";
import { ElTable } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElNotification } from "element-plus";
import { Warning } from "@element-plus/icons-vue";
import Axios from "axios";
import localForage from "localforage";
import * as XLSX from "xlsx";
import FileSaver from "file-saver";
import FileImport from "./fileImport.vue";

const props = defineProps({
  sendDataName: {
    type: String,
    default: "",
  },
  sendConfigName: {
    type: String,
    default: "",
  },
});

const route = useRoute();
const router = useRouter();

interface User {
  // date: string;
  // 标题: string;
  // 内容: string;
  [x: string]: any;
}

const currentPage4 = ref(1);
const pageSize4 = ref(10);
const small = ref(false);
const background = ref(true);
const disabled = ref(false);
let tableData = ref([]);
let total = ref(0);
const visible = ref(false);
let getData = ref();
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<User[]>([]);
const drawer = ref(false);
let btnDisabled = ref(false);
const exportName = ref("");
const dialogVisible = ref(false);
const switchValue = ref(false);
const setTimeValue = ref();
const timer = ref();
const cookieValue = ref<string>(
  "PHPSESSID=pjkgfpulm370t6hedjk5lqemv7; _wtspurl=/xinxicms/index.php?do=manage; _wtsuid=394a0d6d-683d-4bb6-87d4-89ba5d7b84d5; _wtscpk=f192e34c8b; _wtsexp=1666541405; _wtsjsk=60c7c127f986f32657e956e99e728015; agdo__s_uid=%E5%95%86%E5%AE%B6; agdo__s_pwd=UA8CUAACVgEOBFNdDQUDU1EFBAIEBgdTAAJYUldXV1Y%3Dd11b05ebd3"
);
const contentTypeValue = ref(
  "multipart/form-data; boundary=----WebKitFormBoundaryJGRYYBQR89zppt26"
);
const paramValue = ref(`catid: "11",
        title: "宠物测试11111111111",
        areaid: 2,
        endtime: 0,
        content:
          "<span>宠物测试</span><span>宠物测试</span><span>宠物测试</span><span>宠物测试</span>",
        contact_who: "无",
        tel: "无",
        qq: "",
        email: "1931346356@qq.com",
        act: "dopost",
        ismember: 1,
        mixcode: "a325b50ed3f811d0a5d974dc2c57f14a",`);
const urlValue = ref("/api/mayi-post.php?action=input");

const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val;
};

const handleSizeChange = (val: number) => {
  currentPage4.value = 1;
  tableData.value = getData.value.slice(0, val);
};
const handleCurrentChange = (val: number) => {
  tableData.value = getData.value.slice(
    (val - 1) * pageSize4.value,
    val * pageSize4.value
  );
};

const requireSend = async (item: any, newParamsValue: any) => {
  await Axios({
    // url: `/api${urlValue.value}`,
    url: urlValue.value,
    method: "post",
    data: Object.assign(eval("(" + newParamsValue + ")"), {
      title: item.标题,
      content: item.内容,
      catid: item.ID,
    }),
    withCredentials: true,
    headers: {
      "Content-Type": contentTypeValue.value,
    },
  });
};

// 取消定时发布
const calcelSend = () => {
  clearTimeout(timer.value);
};

const releaseAll = () => {
  // 将填写到的信息保存到本地
  localForage.setItem(
    props.sendConfigName,
    JSON.stringify({
      cookie: encodeURIComponent(cookieValue.value),
      contentType: encodeURIComponent(contentTypeValue.value),
      params: encodeURIComponent(paramValue.value),
      url: encodeURIComponent(urlValue.value),
    })
  );
  cookieValue.value.split(";").forEach((item: string) => {
    document.cookie = item;
  });

  const newParamsValue = "{" + paramValue.value + "}";
  multipleSelection.value.forEach(async (item, index) => {
    // 开启定时发布，每隔 n 分钟调用一次
    if (switchValue.value) {
      timer.value = setTimeout(() => {
        requireSend(item, newParamsValue);
        if (index === multipleSelection.value.length - 1) {
          clearInterval(timer.value);
        }
      }, setTimeValue.value * 60 * 1000 * (index + 1));
    } else {
      // 发布
      requireSend(item, newParamsValue);
    }
  });
  drawer.value = false;
  btnDisabled.value = false;
  ElMessage({
    type: "success",
    message: "查看接口的状态，如果状态 = 303，则说明发布成功，否则发布失败",
  });
};

const open1 = () => {
  ElNotification({
    title: "提醒",
    message: h("h3", { style: "color: red" }, "注意修改分类ID"),
    type: "warning",
    duration: 3000,
  });
};

// 提交发布
const mergeData = () => {
  if (
    !cookieValue.value ||
    !contentTypeValue.value ||
    !paramValue.value ||
    !urlValue.value
  ) {
    return ElMessage({
      type: "error",
      message: "请将上面的信息全部填写完整",
    });
  }
  btnDisabled.value = true;
  releaseAll();
};

const submit = async () => {
  if (!multipleSelection.value.length) {
    return ElMessage({
      type: "error",
      message: "请选择表格中的数据",
    });
  }
  const sendDataLocal = await localForage.getItem(props.sendConfigName);
  const getSendData = sendDataLocal && JSON.parse(sendDataLocal as string); // as 类型断言，告诉 ts，返回的值肯定是 string 类型
  if (getSendData) {
    cookieValue.value = decodeURIComponent(getSendData.cookie);
    contentTypeValue.value = decodeURIComponent(getSendData.contentType);
    paramValue.value = decodeURIComponent(getSendData.params);
    urlValue.value = decodeURIComponent(getSendData.url);
  }
  drawer.value = true;
  setTimeout(() => {
    open1();
  }, 300);
};

const gotoFileImport = () => {
  localForage.removeItem(props.sendDataName);
  tableData.value = [];
  total.value = 0;
};

const exportFile = () => {
  if (!tableData.value.length) {
    return ElMessage({
      type: "error",
      message: "表格无数据，无法导出",
    });
  }
  if (!multipleSelection.value.length) {
    return ElMessage({
      type: "error",
      message: "请选择表格中的数据",
    });
  }
  if (!exportName.value.trim()) {
    return ElMessage({
      type: "error",
      message: "请填写文件名",
    });
  }
  visible.value = false;
  var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
  var table: any = document.querySelector("#exportDom")?.cloneNode(true);
  // table?.removeChild(table.querySelector(".el-table__fixed")); //这里是双下划线
  var wb = XLSX.utils.table_to_book(table, xlsxParam);
  var wbout = XLSX.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(
      new Blob([wbout], { type: "application/octet-stream" }),
      `${exportName.value.trim()}.xlsx`
    );
  } catch (e) {
    console.log(e, 111112)
    if (typeof console !== "undefined") {
      ElMessage({
        type: "error",
        message: "文件导出失败",
      });
    }
  }
};

const fileImportResult = (data: any) => {
  ElMessage({
    type: "success",
    message: "文件导入成功",
  });
  dialogVisible.value = false;
  getData.value = data;
  tableData.value = getData.value.slice(0, 10);
  total.value = getData.value.length;
  localForage.setItem(
    props.sendDataName,
    encodeURIComponent(JSON.stringify(data))
  );
};

const getLocalData = async () => {
  const localNewData = await localForage.getItem(props.sendDataName);
  if (!localNewData) return;
  getData.value = JSON.parse(decodeURIComponent(localNewData as string));
  tableData.value = getData.value.slice(0, 10);
  total.value = getData.value.length;
};

onMounted(() => {
  getLocalData();
});

onBeforeUnmount(() => {
  gotoFileImport();
});
</script>

<style scoped>
.table-list {
  width: 100%;
  height: 100%;
  max-height: calc(100% - 60px);
  /* overflow-y: scroll; */
}
.pagination-list {
  width: 100%;
  height: 50px;
  margin-top: 10px;
  background-color: #f4f4f5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.input-box {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.box-title {
  width: 130px;
}

.footer-sty {
  position: fixed;
  right: 20%;
  bottom: 0;
  margin-bottom: 20px;
}

.tip-send {
  /* background-color: #C0C4CC; */
  /* padding: 6px; */
  border-radius: 10px;
  /* font-weight: 600; */
}

.success-send {
  width: 100%;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.success-send img {
  width: 80%;
  height: 60px;
}

.fail-send {
  width: 100%;
  line-height: 28px;
}

.export-sty {
  margin: 20px 0;
}

.import-tip {
  color: red;
  font-weight: 600;
  display: flex;
  align-items: center;
}
</style>
